from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError
import time
import os
from dotenv import load_dotenv

# Load environment variables if using a .env file
load_dotenv()

def login_to_facebook(email: str, password: str):
    """
    Logs in to Facebook, searches for a topic, and retrieves post content and reactions.
    
    Args:
        email (str): Facebook account email.
        password (str): Facebook account password.
    """
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=100)
        page = browser.new_page()
        page.context.add_cookies([
            {
                "name": "c_user",
                "value": "100004167219411",
                "domain": ".facebook.com",
                "path": "/"
            },
            {
                "name": "xs",
                "value": "37%3AnQ16poPNXOYHhA%3A2%3A1741318601%3A-1%3A8696%3A%3AAcUXOnsEZeWm1b5_-iEDAMNOJjAVgC2mWP6Gpu5P4w",
                "domain": ".facebook.com",
                "path": "/"
            }
        ])
        
        page.set_viewport_size({"width": 1920, "height": 1080})  # Set viewport size to maximize
        # Navigate to Facebook login page
        page.goto("https://www.facebook.com/AFKJourneyOfficial")
    
        # page.query_selector("input[name='email'][id]").fill(email)
        # page.query_selector("input[name='pass'][id]").fill(password)
        # page.locator('xpath=//*[@id="login_popup_cta_form"]/div/div[6]/div/div').first.click()

        if not wait_for_page_to_load(page):
            browser.close()
            return

        if not navigate_to_first_post(page):
            browser.close()
            return

        post_urls = get_post_urls(page)
        print(f"找到的帖子链接: {post_urls}")
        
        browser.close()

def wait_for_page_to_load(page):
    """Waits for the Facebook homepage to load after logging in."""
    try:
        page.wait_for_selector('div.x1yztbdb.x1n2onr6.xh8yej3.x1ja2u2z', timeout=40000)
        return True
    except PlaywrightTimeoutError:
        print("Timeout waiting for the page to load after login")
        return False

def navigate_to_first_post(page):
    """Navigates to the first post after searching for the topic."""
    try:
        posts = page.locator("div.x1yztbdb.x1n2onr6.xh8yej3.x1ja2u2z")
        if posts.count() > 0:
            return True
        print("No posts found.")
        return False
    except PlaywrightTimeoutError:
        print("Timeout waiting for posts to load")
        return False

def get_post_urls(page):
    """提取帖子url"""

    # print("正在加载所有帖子...")
    load_all_posts(page)

    print("正在提取帖子url...")

    post_urls = []
    post_links = page.query_selector_all('//div[@data-pagelet="ProfileTimeline"]//a[contains(@href, "www.facebook.com/AFKJourneyOfficial/posts")]')

    print(f"找到的帖子数量: {len(post_links)}")

    for link in post_links:
        href = link.get_attribute('href')
        if href:
            post_urls.append(href)
            print(f"找到帖子链接: {href}")
    
    return post_urls

def load_all_posts(page):
    """Loads all posts on the page."""
    print("正在加载所有帖子...")
    # 初始滚动次数
    scroll_count = 0
    max_scrolls = 10  # 最大滚动次数，可以根据需要调整

    while scroll_count < max_scrolls:
        # 检查目标元素的子元素是否为空
        target_element = page.locator('div[data-pagelet="ProfileTimeline"] > div.x1xzczws')
        if target_element.count() <= 0:
            break
        page.mouse.wheel(0, 1000)
        time.sleep(2)
        scroll_count += 1
    print("页面滚动完成")

def main():
    """Main function to call the login_facebook function with example arguments."""
    email = os.getenv("FACEBOOK_EMAIL")
    password = os.getenv("FACEBOOK_PASSWORD")
    if not email or not password:
        print("Email or password environment variables not set.")
        return

    login_to_facebook(email, password)

if __name__ == "__main__":
    main()
